import React, { useState } from 'react'
import Demo2page from './demo2page'
// @ts-ignore
import FibonacciWorker from './fibonacci.worker'

export default function App() {
  const [inputValue,setInputValue] = useState<any>(10);
  const [workerResult,setWorkerResult] = useState();

  const send = ()=>{
    // 发送消息
    const message = {
      type: 'hello',
      data: 'Hello, world!'
    };
    const targetOrigin = 'http://localhost:9001'; // 指定目标窗口的URL
    window.postMessage(message, targetOrigin);
  }
  const send2 = ()=>{
    // 获取目标窗口对象
    const targetWindow = window.parent; // 或者使用window.opener获取打开当前窗口的窗口对象
    // 发送消息
    const message = {
      type: 'hello',
      data: '来自子级页面Hello, world!'
    };
    const targetOrigin = 'http://localhost:9000'; // 指定目标窗口的URL
    targetWindow.postMessage(message, targetOrigin);
  }
  const workerHandler = ()=>{
    if(window.Worker) {
      var worker = new FibonacciWorker();
      worker.postMessage(inputValue * 1);
      worker.onmessage = function(event:any) {
        setWorkerResult(event.data);
      };
    }
  }
  return (
    <div>
      <h1>window2</h1>
      <button onClick={send}>发送给同源数据</button>
      <button onClick={send2}>发送给父级页面（跨域）</button>
      <div style={{border:'1px solid red'}}>
        <h2>通过Worker、postMessage来计算耗时数据，不占用主线程，计算完成后返回给主线程</h2>
        <h1>WebWorker和postMessage示例</h1>
        <p>计算斐波那契数列的第n项：</p>
        {/*  @ts-ignore*/}
        <input type="number"min="1" max="100" value="10" value={inputValue} onChange={(e)=>{
            setInputValue(e.target.value)
        }}/>
        <button onClick={workerHandler}>计算</button>
        <p>计算的结果是：{workerResult}</p>
      </div>
      <Demo2page></Demo2page>
    </div>
  )
}
